package game.module.nn.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.HallServer;
import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.nn.bean.NnRoom;
import game.module.nn.logic.NnDataManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageNn.C2SNNBeginFight;
import lua.LuaMessageNn.S2CNNBeginFight;

@MsgCodeAnn(msgcode = C2SNNBeginFight.id, accessLimit = 500)
public class NnConfirmFightProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(NnConfirmFightProcessor.class);

	@Override
	public void process(PlayingRole hero, RequestMessageRaw request) throws Exception {
		int playerId = hero.getId();
		logger.info("nn confirm fight,playeyId={}", playerId);
		// 是否在房间中
		boolean isInRoom = NnDataManager.getInstance().isPlayerInRoom(playerId);
		if (!isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// is room exist
		final NnRoom ddzRoom = NnDataManager.getInstance().getNnRoomByPlayerId(playerId);
		if (ddzRoom == null) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// 人数不足
		if (ddzRoom.getPlayerList().size() < 2) {
			S2ErrorCode respMsg = new S2ErrorCode(301);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// ret
		S2CNNBeginFight retMsg = new S2CNNBeginFight();
		hero.writeAndFlush(retMsg.build(hero.alloc()));
		// delay 2 seconds to start
		sendRoomStart(ddzRoom);
	}

	private void sendRoomStart(NnRoom ddzRoom) {
		logger.info("nn start battle!");
		String rsLanHost = HallServer.getInstance().getServerConfig().getRsLanHost();
		int rsLanPort = HallServer.getInstance().getServerConfig().getRsLanPort();
		boolean reconnectRet = HallServer.getInstance().getLanClientManager().connect(rsLanHost, rsLanPort);
		if (reconnectRet) {
			HallServer.getInstance().getLanClientManager().sendNnStart2Rs(rsLanHost, rsLanPort, ddzRoom);
		} else {
			logger.error("connect 2 roomServer error!rsLanHost={},rsLanPort={}", rsLanHost, rsLanPort);
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// null
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// null
	}

}
